<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="q.level" class="filter-item" placeholder="请选择级别" clearable>
        <el-option
          label="全部"
          value=""
        >
        </el-option>
        <el-option
          v-for="item in alarmLogLevelOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <div class="filter-item">
        <el-input v-model="q.component" clearable placeholder="关键字"/>
      </div>
      <div class="filter-item">
        <el-date-picker
          v-model="q.startTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择开始时间"
        >
        </el-date-picker>
      </div>
      <div class="filter-item">
        <el-date-picker
          v-model="q.endTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择结束时间"
        >
        </el-date-picker>
      </div>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <!--<el-button class="filter-item" type="danger" icon="el-icon-delete" @click="deleteAlarmLog()">批量删除</el-button>
      <el-button class="filter-item" type="danger" icon="el-icon-delete-solid" @click="deleteAllAlarmLog">删除全部</el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="exportAlarmLogs"
      >导出
      </el-button>-->
      <div class="filter-item pull-right">
        <span class="label-text">自动刷新</span>
        <el-switch v-model="autoRefresh"></el-switch>
      </div>
    </div>
    <el-table
      :key="tableKey"
      v-loading="tableLoading"
      :data="logs"
      border
      fit
      highlight-current-row
      :row-class-name="tableRowClassName"
      style="width: 100%;"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column label="创建时间" align="center" width="230">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime("{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="级别" prop="level" align="center" width="90"></el-table-column>
      <el-table-column label="主体" prop="component" min-width="120"></el-table-column>
      <el-table-column label="事件" prop="event" min-width="120"></el-table-column>
      <el-table-column label="更新时间" align="center" width="230">
        <template slot-scope="{row}">
          <span>{{ row.updateTime | parseTime("{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="操作" align="center" width="90" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" type="danger" @click="deleteAlarmLog(row.id)">删除</el-button>
        </template>
      </el-table-column>-->
    </el-table>
    <pagination
      v-show="totalCount > 0"
      :total="totalCount"
      :page-index.sync="q.page"
      :page-size.sync="q.size"
      @pagination="getAlarmLogsPage"
    />
  </div>
</template>

<script>
  import {
    getAlarmLogsPage,
    exportAlarmLogs,
    deleteAlarmLog,
    deleteAllAlarmLog
  } from "@/api/log";
  import { alarmLogLevelOptions } from '@/utils/enums.js';
  import Pagination from "@/components/Pagination";
  import _ from "lodash";

  export default {
    components: {
      'pagination': Pagination
    },
    data() {
      return {
        alarmLogLevelOptions,
        isSubmitLoading: false,
        downloadLoading: false,
        tableLoading: false,
        tableKey: 0,
        itemsChecked: [],
        logs: [],
        q: {
          page: 1,
          size: 10,
          component: undefined,
          startTime: undefined,
          endTime: undefined,
          level: undefined
        },
        autoRefresh: true,
        totalCount: 0,
        timer: undefined
      };
    },
    computed: {},
    watch: {
      autoRefresh: function(newVal) {
        if (newVal) {
          this.setInterval();
        } else {
          clearInterval(this.timer);
        }
      }
    },
    destroyed() {
      clearInterval(this.timer);
    },
    created() {
      this.getAlarmLogsPage();
      this.setInterval();
    },
    methods: {
      selectionChange(selection) {
        this.itemsChecked = selection;
      },
      setInterval() {
        this.timer = setInterval(() => {
          this.getAlarmLogsPage();
        }, 5000);
      },
      handleSearch() {
        this.getAlarmLogsPage();
      },
      getAlarmLogsPage() {
        if (this.q.hasOwnProperty("password")) {
          delete this.q.password;
        }
        this.tableLoading = true;
        // 根据id查询某个通道信息
        getAlarmLogsPage(this.q).then(result => {
          this.logs = result.content;
          this.totalCount = result.totalElements;
          this.tableLoading = false;
        });
      },
      tableRowClassName({ row, rowIndex }) {
        if (row.level === "ERROR") {
          return 'danger-row';
        }
        return '';
      },
      exportAlarmLogs() {
        this.$prompt('请为导出文档设置密码（必填，请谨记）', '请输入密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S/,
          inputErrorMessage: '文档密码不能为空'
        }).then(({ value }) => {
          const loading = this.$loading({
            lock: true,
            text: '请稍候...',
            spinner: 'el-icon-loading',
            background: 'rgba(255, 255, 255, 0.7)'
          });
          this.q.password = value;
          exportAlarmLogs(this.q).then(result => {
            this.download(result, '告警日志.xlsx');
            loading.close();
          });
        }).catch(() => {

        });
      },
      download(data, name) {
        const blob = new Blob([data]);
        const fileName = name;
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
        this.downloadLoading = false;
      },
      deleteAllAlarmLog() {
        this.$confirm("删除后不可恢复， 是否继续?", "确定执行全部删除操作吗？", {
          type: "warning"
        })
          .then(() => {
            deleteAllAlarmLog().then(() => {
              this.getAlarmLogsPage();
              this.$message({ message: "删除成功", type: "success" });
            });
          })
          .catch(() => {
          });
      },
      deleteAlarmLog(id) {
        let selectedIds = [];
        if (id) {
          selectedIds = [id];
        } else {
          selectedIds = this.itemsChecked.map(item => _.parseInt(item.id));
          if (selectedIds.length <= 0) {
            this.$message({ message: "至少选中一条记录", type: "warning" });
            return;
          }
        }

        this.$confirm("删除后不可恢复， 是否继续?", "确定执行删除操作吗？", {
          type: "warning"
        })
          .then(() => {
            deleteAlarmLog(selectedIds).then(() => {
              this.getAlarmLogsPage();
              this.$message({ message: "删除成功", type: "success" });
            });
          })
          .catch(() => {
          });
      }
    }
  };
</script>

<style lang="scss">
  .el-table .danger-row {
    color: #F56C6C !important;
  }
</style>
